﻿using GameCore;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


//SH的游戏主逻辑
public class MainLogic : MonoBehaviour {

    //用来 1初始化状态机  2change状态  3update实时监控状态  4 当前状态判断
    public GameCore.UiStateManager uiStateManager { get; set; }  

    void Awake()
    {
        DontDestroyOnLoad(transform.gameObject);
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
        Screen.orientation = ScreenOrientation.LandscapeLeft;
        Screen.orientation = ScreenOrientation.AutoRotation;

#if UNITY_IPHONE
        Application.targetFrameRate = 60;
#else
        Application.targetFrameRate = 30;
#endif
 
       //获取地理位置
#if UNITY_EDITOR 
#else
            Debug.Log("获取地理位置");
            LoginAndShare.Controller.GetPlaceInfo();
#endif
        //注册界面
        UIManager.PageInit();
        //注册状态机
        uiStateManager = new GameCore.UiStateManager((int) GameCore.UIState.UIState_None, null, this.gameObject);
        uiStateManager.Init();
        //音频管理器注册  TODO
        //UI管理器注册 TODO
    }


    void Start () {	
	}
	
	void Update () {
        //实时监控退出键按下
        OnBackBtnCLick();
        //实时监控UI状态的改变
        uiStateManager.Update();
	}

    //改变状态，通过设置下一个状态来改变
    public void ChangeState(int StateId)
    {
        uiStateManager.SetNextSubState(StateId);
    }

    //设置音乐
    AudioSource aud;
    public void SetBGMusic()
    {
        aud = GameObject.Find("StaticSource").GetComponent<AudioSource>();
        aud.clip = Resources.Load<AudioClip>("Music/SoundEffect_Common/backmusic1");
        aud.volume = PlayerPrefs.GetFloat("Music", 0.33f);    //这里获取声音设置，如果没有设置返回0.33
    }

    public void SetFightMusic()
    {
        aud = GameObject.Find("StaticSource").GetComponent<AudioSource>();
        aud.clip = Resources.Load<AudioClip>("Music/背景");
        aud.volume = PlayerPrefs.GetFloat("Music", 0.33f);
    }


    private bool isDown = false;
    private bool isUp = false;
    //设置返回键退出功能
    public void OnBackBtnCLick()
    {
        if (uiStateManager.NextSubStateID == (int)UIState.UIState_None || uiStateManager.CurrentSubStateID() == (int)UIState.UIState_SHLoadingState)
        {
            return;
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            isDown = true;
        }

        if (Input.GetKeyUp(KeyCode.Escape))
        {
            isUp = true;
        }

        if (isDown && isUp)
        {
            ShowExitGameTipsPage();
            isDown = false;
            isUp = false;
        }
    }

    public void ShowExitGameTipsPage()
    {
        GameObject tipsPage = GameObject.Find("SpecialCanvas/SpecialAddNode/TipsHaveCancelPage(Clone)");
        if (tipsPage)
        {
            DestroyImmediate(tipsPage);
        }
        else
        {
            TooL.ShowTipsPage("确认退出游戏？", TooL.TipsPageType.haveCancelPage, () => Application.Quit());
        }
    }
}
